/**
 * Copyright (c) iwindplus Technologies Co., Ltd.2024-2030, All rights reserved.
 */

package com.iwindplus.gateway.server.filter;

import cn.hutool.core.text.CharSequenceUtil;
import com.iwindplus.base.domain.constant.CommonConstant.ApiSignConstant;
import com.iwindplus.base.domain.constant.CommonConstant.HeaderConstant;
import com.iwindplus.base.util.HttpsUtil;
import com.iwindplus.base.util.ReactorUtil;
import com.iwindplus.gateway.server.domain.constant.GatewayConstant.FilterConstant;
import com.iwindplus.gateway.server.domain.constant.GatewayConstant.ServerWebExchangeContextConstant;
import com.iwindplus.gateway.server.domain.property.GatewayProperty;
import com.iwindplus.gateway.server.util.GatewayUtil;
import java.util.concurrent.TimeUnit;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 基础过滤器.
 *
 * @author zengdegui
 * @since 2020/4/15
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class BaseFilter implements Ordered, GlobalFilter {

    private final GatewayProperty property;

    @Override
    public int getOrder() {
        return FilterConstant.FILTER_BASE_ORDER;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        final long start = System.nanoTime();
        final long beginMillis = System.currentTimeMillis();
        // 设置请求开始时间
        ReactorUtil.setAttribute(exchange, ServerWebExchangeContextConstant.REQUEST_TIME, beginMillis);

        ServerHttpRequest req = exchange.getRequest();
        HttpsUtil.removeForgeHeader(exchange);

        String path = req.getPath().value();
        String prefix = GatewayUtil.getApiPrefix(exchange);
        if (CharSequenceUtil.isNotBlank(prefix)
            && property.getApiSign().getEnabledRelativePath()
            && path.startsWith(prefix)
            && path.length() > prefix.length()) {
            path = path.substring(prefix.length());
        }
        String lang = GatewayUtil.getLang(req);
        String realIp = GatewayUtil.getRealIp(exchange);

        log.debug("path={}, lang={}, realIp={}, prefix={}", path, lang, realIp, prefix);

        String finalPath = path;
        ServerHttpRequest newReq = req.mutate()
            .headers(h -> {
                h.add(ApiSignConstant.X_PATH, finalPath);
                h.add(HttpHeaders.ACCEPT_LANGUAGE, lang);
                h.add(HeaderConstant.REAL_IP, realIp);
                h.add(HeaderConstant.X_FORWARDED_PREFIX, prefix);
            })
            .build();

        return chain.filter(exchange.mutate().request(newReq).build())
            .doFinally(signal -> log.info("{} execute cost={} ms", this.getClass().getSimpleName(),
                TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start)));
    }

}
